using System;
using System.IO;
using CosyTrade.Core;

namespace CosyTrade.DataStorage
{
    [Addin("DataStorage")]
    public class DataStorage : AddinBase, IDataStorage
    {
        private string saveBasePath;

        protected override void OnInitialize()
        {
            saveBasePath = ConfigNode["DataStroagePath"].InnerText;
            if (saveBasePath == "/")
                saveBasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data");
            if (!Directory.Exists(saveBasePath))
                Directory.CreateDirectory(saveBasePath);
        }

        public void SaveData(Guid saveMark, byte[] data)
        {
            string savePath = getFilename(saveMark);
            using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None))
                fs.Write(data, 0, data.Length);
        }

        public byte[] GetData(Guid saveMark)
        {
            string savePath = getFilename(saveMark);
            if (!File.Exists(savePath)) return null;
            using(FileStream fs = new FileStream(savePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                byte[] reVal = new byte[fs.Length];
                fs.Read(reVal, 0, reVal.Length);
                return reVal;
            }
        }

        public void DeleteData(Guid saveMark)
        {
            string savePath = getFilename(saveMark);
            if (!File.Exists(savePath)) return ;
            File.Delete(savePath);
        }

        private string getFilename(Guid saveMark)
        {
            return Path.Combine(saveBasePath, string.Format("{0}.trc", saveMark.ToString("N"))); 
        }
    }
}